#!/bin/sh

mtk_wifi_e2p_die() {
	echo "mtk wifi eeprom: " "$*"
	exit 1
}

mtk_wifi_e2p_extract() {
	local part=$1
	local offset=$2
	local count=$3
	local mtd

	. /lib/functions.sh

	mtd=$(find_mtd_part $part)
	mtd=`echo $mtd | sed -e 's/mtdblock/mtd/'`

	cmd=`which nanddump`

	[ -n "$mtd" ] || \
		mtk_wifi_e2p_die "no mtd device found for partition $part"

	if [ -z "$cmd" ]; then
		dd if=$mtd of=/lib/firmware/$FIRMWARE bs=$count skip=$offset count=1 2>/dev/null || \
			mtk_wifi_e2p_die "failed to extract from $mtd"
	else
		nanddump -f /lib/firmware/$FIRMWARE $mtd 2>/dev/null || \
			mtk_wifi_e2p_die "failed to extract from $mtd"
	fi
}

[ -f "/etc/wireless/l1profile.dat" ] || exit 0
# first line "Default" is illegal in shell
cat /etc/wireless/l1profile.dat | tail -n +2 > /tmp/l1profile.sh

. /tmp/l1profile.sh

[ "$FIRMWARE" != "" ] || FIRMWARE=$INDEX0_EEPROM_name
FW="/lib/firmware/$FIRMWARE"
[ -e "$FW" ] && exit 0

# This is the ideal way, but driver does not follow...
# case "$FIRMWARE" in
# $INDEX0_EEPROM_name)
# 	mtk_wifi_e2p_extract "Factory" `printf "%d" $INDEX0_EEPROM_offset` `printf "%d" $INDEX0_EEPROM_size`
# 	;;
# $INDEX1_EEPROM_name)
# 	mtk_wifi_e2p_extract "Factory" `printf "%d" $INDEX1_EEPROM_offset` `printf "%d" $INDEX1_EEPROM_size`
# 	;;
# $INDEX2_EEPROM_name)
# 	mtk_wifi_e2p_extract "Factory" `printf "%d" $INDEX2_EEPROM_offset` `printf "%d" $INDEX2_EEPROM_size`
# 	;;
# esac

# Then here's the compromised way

case "$FIRMWARE" in
$INDEX2_EEPROM_name)
	l1_e2p_offset=`printf "%d" $INDEX2_EEPROM_offset`
	l1_e2p_size=`printf "%d" $INDEX2_EEPROM_size`
	final_size=`expr $l1_e2p_offset + $l1_e2p_size`
	mtk_wifi_e2p_extract "Factory" 0 $final_size
	;;
$INDEX1_EEPROM_name)
	l1_e2p_offset=`printf "%d" $INDEX1_EEPROM_offset`
	l1_e2p_size=`printf "%d" $INDEX1_EEPROM_size`
	final_size=`expr $l1_e2p_offset + $l1_e2p_size`
	mtk_wifi_e2p_extract "Factory" 0 $final_size
	;;
$INDEX0_EEPROM_name)
	l1_e2p_offset=`printf "%d" $INDEX0_EEPROM_offset`
	l1_e2p_size=`printf "%d" $INDEX0_EEPROM_size`
	final_size=`expr $l1_e2p_offset + $l1_e2p_size`
	mtk_wifi_e2p_extract "Factory" 0 $final_size
	;;
esac

rm -f /tmp/l1profile.sh

